<?php

namespace app\manystore\controller\salescenter;

use app\common\controller\ManystoreBase;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

use think\Db;
use app\manystore\Model\UserModel;
use app\manystore\Model\UserInfo;
use app\manystore\Model\CampusClewConsultantModel;
use app\manystore\Model\ManystoreModel;
use app\manystore\Model\CampusStudentSourceModel;
use app\manystore\Model\CampusClewlabelModel;
use app\manystore\Model\CourseModel;
use app\manystore\Model\CampusFollowModel;
use app\manystore\Model\TypeModel;
use app\manystore\Model\GrowthPortfolioModel;
use app\manystore\Model\CampusClassStudent;
use app\manystore\Model\CampusClassDateRecord;
use app\manystore\Model\CampusCourseOrderSublevel;
/**
 * 线索接口
 */
class Clue extends ManystoreBase
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $auth = [];

    public function _initialize()
    {
        parent::_initialize();
    }

    private function AuthParams($auth = [])
    {
        $param_tmp = $this->request->param();
        $param = [];
        foreach ($auth as $key => $value)
        {
            if(isset($param_tmp[$value]))
            {
                $param[$value] = $param_tmp[$value];
            }
        }

        return $param;
    }

    /**
     * 添加线索
     *
     * @ApiTitle    添加线索
     * @ApiMethod   (POST)

     * @ApiParams (name="truename", type="string", required=true, description="学员姓名")
     * @ApiParams (name="mobile_identity", type="integer", required=true, description="谁的手机号:0=无,1=本人,2=妈妈,3=爸爸,4-爷爷,5=奶奶,6=外公,7=外婆")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="gender", type="integer", required=false,description="性别:0=未知,1=男,2=女")
     * @ApiParams (name="agebirthday", type="integer", required=true,description="年龄或生日:0=年龄,1=生日")
     * @ApiParams (name="age_year", type="integer", required=false,description="年龄【几岁】")
     * @ApiParams (name="age_month", type="integer", required=false,description="年龄【几个月】")
     * @ApiParams (name="birthday", type="date", required=false,description="生日【格式：2020-01-01】")
     * @ApiParams (name="standbycontact_identity", type="integer", required=false,description="谁的备用号码:0=无,1=本人,2=妈妈,3=爸爸,4-爷爷,5=奶奶,6=外公,7=外婆")
     * @ApiParams (name="standby_contact", type="string", required=false,description="手机号")
     * @ApiParams (name="home_address", type="string", required=true,description="家庭地址")
     * @ApiParams (name="intention_level", type="integer", required=true,description="意向级别:1=低,2=中,3=高")
     * @ApiParams (name="students_source", type="string", required=true,description="学员来源【ID号，可多选，以,分隔】")
    
     * @ApiParams (name="allocation_towho", type="integer", required=true, description="分配给谁:1=课程顾问,2=公有池")
     * @ApiParams (name="course_consultant", type="integer", required=false, description="顾问【选择分配为课程顾问时必填】")
     * @ApiParams (name="collect_people", type="integer", required=true, description="采单人")
     * @ApiParams (name="label", type="string", required=false, description="标签【ID号，多项以,分隔】")
     * @ApiParams (name="consult_course", type="string",required=false,description="咨询课程【分配为课程顾问时必填，ID号，多项以,分隔】")
     * @ApiParams (name="remark", type="string", required=false, description="备注")
     * @ApiParams (name="avatar", type="string", required=false, description="头像路径【文件上传API接口返回参数url】")
     * @ApiSector   销售中心
     * @ApiReturn   ({
        'code' : '1',
        'msg' : '返回成功',
        'time' : '1657378506',
        'data' : null
     * })
     */
    public function addClue()
    {
        #允许传入的参数
        $auth_params = ['truename','mobile_identity','mobile','gender','agebirthday','age_year','age_month','birthday','standbycontact_identity','standby_contact','home_address','intention_level','students_source','consult_course','allocation_towho','collect_people','label','remark','avatar','course_consultant'];
        $param = $this->AuthParams($auth_params);

        if(empty($param['truename']))
        {
            $this->error('姓名不能为空');
        }

        if($param['mobile_identity'] < 0 || $param['mobile_identity'] > 7)
        {
            $this->error('请选择手机号所属人');
        }

        if(empty($param['mobile_identity']))
        {
            #若选择手机所属人为无，手机号则为空
            $param['mobile'] = '';
        }
        else if(!preg_match('/^1[3-9][\d]{9}$/', $param['mobile']))
        {
            $this->error('请输入正确的手机号');
        }

        if(empty($param['gender']) || $param['gender'] < 0 || $param['gender'] > 2)
        {
            $param['gender'] = 0;
        }

        if($param['agebirthday'] == 0)
        {
            if($param['age_year'] < 0 || $param['age_year'] > 109)
            {
                $this->error('请正确填写年龄(几岁)');
            }

            if($param['age_month'] < 0 || $param['age_month'] > 999)
            {
                $this->error('请正确填写年龄(几岁)');
            }

            $year_diff = intval(date('Y') - $param['age_year']);
            $month_diff = intval(date('m') - $param['age_month']);
            if($month_diff < 0)
            {
                $year_diff--;
                $month_diff = intval(12 +  $month_diff);
            }

            $param['birthday'] = $year_diff.'-'.$month_diff.'-01';
        }
        else if($param['agebirthday'] == 1)
        {
            if(!preg_match('/^[12][\d]{3}-(([1][0-2])|([0][\d]))-(([0][\d])|([1][\d]))$/', $param['birthday']))
            {
                $this->error('请正确填写年龄(几岁)');
            }

            $param['age_year'] = 0;
            $param['age_month'] = 0;
            
            $birthday = explode('-',$param['birthday']);

            $year_diff = intval(date('Y') - $birthday[0]);
            $month_diff = intval(date('m') - $birthday[1]);

            if($month_diff < 0)
            {
                $year_diff--;
                $month_diff = intval(12 +  $month_diff);
            }
            $param['age_year'] = $year_diff;
            $param['age_month'] = $month_diff;
        }

        if($param['standbycontact_identity'] < 0 || $param['standbycontact_identity'] > 7)
        {
            $this->error('请选择备用手机号所属人');
        }

        if(empty($param['standbycontact_identity']))
        {
            #若选择手机所属人为无，手机号则为空
            $param['standby_contact'] = '';
        }
        else if(!preg_match('/^1[3-9][\d]{9}$/', $param['standby_contact']))
        {
            $this->error('请输入正确的备用手机号');
        }
        else if($param['standby_contact'] == $param['mobile'])
        {
            $this->error('备用手机号不能与常用手机号相同');
        }

        if(empty($param['home_address']))
        {
            $this->error('请输入家庭地址');
        }

        if($param['intention_level'] < 1 || $param['intention_level'] > 3)
        {
            $this->error('请选择意向级别');
        }

        if(!empty($param['students_source']))
        {
            $param['students_source'] = explode(',', $param['students_source']);
            $students_source_ids = [];
            foreach ($param['students_source'] as $key => $value)
            {
                $students_source_ids[] = intval($value);
            }
            $students_source_ids = !empty($students_source_ids) ? implode(',', $students_source_ids) : '';

            $students_source_info = TypeModel::field('id')->where('type','studentsource')->where('id','in',$students_source_ids)->select();

            $param['students_source'] = [];
            foreach ($students_source_info as $key => $value) {
                $param['students_source'][] = $value['id'];
            }

            $param['students_source'] = !empty($param['students_source']) ? implode(',', $param['students_source']) : '';
        }

        if(empty($param['students_source']))
        {
            $this->error('请选择学员来源');
        }

        if($param['allocation_towho'] == 1)
        {
            if(!empty($param['course_consultant']))
            {
                $param['course_consultant'] = explode(',', $param['course_consultant']);
                $course_consultant_ids = [];
                foreach ($param['course_consultant'] as $key => $value)
                {
                    $course_consultant_ids[] = intval($value);
                }
                $course_consultant_ids = !empty($course_consultant_ids) ? implode(',', $course_consultant_ids) : '';

                $students_source_info = CampusClewConsultantModel::field('id')->where('id','in',$course_consultant_ids)->select();

                $param['course_consultant'] = [];
                foreach ($students_source_info as $key => $value) {
                    $param['course_consultant'][] = $value['id'];
                }

                $param['course_consultant'] = !empty($param['course_consultant']) ? implode(',', $param['course_consultant']) : '';
            }

            if(empty($param['course_consultant']))
            {
                $this->error('请选择课程顾问');
            }
        }
        else if($param['allocation_towho'] == 2)
        {
            #若选择分配为公有池
            $param['is_publicpool'] = 1;
            $param['publicpool_time'] = time();//更新进入公有池时间
            $param['follow_status'] = 1;

            $param['course_consultant'] = 0;//未分配顾问则默认为0
        }
        else
        {
            $this->error('请选择分配对象');
        }

        $param['collect_people'] = !empty($param['collect_people']) ? intval($param['collect_people']) : $this->auth->id;
        $collect_people_info = ManystoreModel::get($param['collect_people']);
        if(empty($collect_people_info))
        {
            $this->error('请选择采单人');
        }

        // if(empty($param['label']))
        // {
        //     $this->error('请选择标签');
        // }

        if(!empty($param['consult_course']))
        {
            $param['consult_course'] = explode(',', $param['consult_course']);

            $consult_course_ids = [];
            foreach ($param['consult_course'] as $key => $value)
            {
                $consult_course_ids[] = intval($value);
            }
            $consult_course_ids = !empty($consult_course_ids) ? implode(',', $consult_course_ids) : '';

            $consult_course_info = CourseModel::field('id')->where('status',1)->where('id','in',$consult_course_ids)->select();

            $param['consult_course'] = [];
            foreach ($consult_course_info as $key => $value) {
                $param['consult_course'][] = $value['id'];
            }

            $param['consult_course'] = !empty($param['consult_course']) ? implode(',', $param['consult_course']) : '';
        }
        if($param['allocation_towho'] == 1 && empty($param['consult_course']))
        {
            $this->error('请选择咨询课程');
        }

        if(!is_file('.'.$param['avatar']))
        {
            $this->error('请上传头像');
        }

        $param['shop_id'] = $collect_people_info['shop_id'];#跟随采单人
        $param['create_admin'] = $this->auth->id;#创建时添加自己为创建人

        // 启动事务
        Db::startTrans();
        try
        {
            //新增校园_销售中心_线索表
            $usermodel = new UserModel;
            $usermodel->save($param);
            $new_uid = $usermodel->id;

            //新增用户线索表
            $userinfo_params = ['u_id' => $new_uid,'allot' => $param['allocation_towho'],'allot_id' => $param['course_consultant'],'adopt_id' => $param['collect_people']];
            $userinfomodel = new UserInfo;
            $userinfomodel->save($userinfo_params);

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('添加线索失败');
        }

        $this->success('添加线索成功','');
    }

    /**
     * 删除线索
     *
     * @ApiTitle    删除线索

     * @ApiParams (name="student_id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="delete_why", type="integer", required=false, description="删除原因")
     * @ApiParams (name="delete_type", type="integer", required=false, description="删除方式【1=进入回收站，2=彻底删除】")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657964522",
          "data": [
            {
              "createtime": "2022-06-08 11:17:59",//记录时间
              "operation_user": "思明校区",//操作人
              "content": "测试评价",//评价
              "from": "teacher"//self来自自己，teacher来自老师
            },
            ......
          ]
        })
     */
    public function delClue()
    {
        #允许传入的参数
        $auth_params = ['student_id','delete_why','delete_type'];
        $param = $this->AuthParams($auth_params);

        $student_id = intval($this->request->param('student_id'));
        $delete_why = intval($this->request->param('delete_why'));
        $delete_type = intval($this->request->param('delete_type'));

        $info = UserModel::get($student_id);

        if(empty($info))
        {
            $this->error('线索不存在');
        }

        if($delete_type == 1 && $info['delete_admin'] > 0)
        {
            $this->error('线索已进入回收站');
        }

        if($info['follow_uid'] > 0 && $info['follow_uid'] != $this->auth->id)
        {
            $this->error('你不是该线索的跟进人,无法执行删除操作');
        }
        else if($info['follow_uid'] != $this->auth->id && $info['create_admin'] != $this->auth->id)
        {
            $this->error('你不是该线索的跟进人或创建人,无法执行删除操作');
        }
        else if($info['student_type'] == 3)
        {
            $this->error('该线索为历史线索,无法执行删除操作');
        }

        if($delete_type != 2)
        {
            if(empty($delete_why))
            {
                $this->error('请选择删除原因');
            }

            $delete_why_info = TypeModel::where(['id' => $delete_why,'type' => 'delwhy'])->find();
            if(empty($delete_why_info))
            {
                $this->error('请选择删除原因');
            }

            $info->deletetime = time();
            $info->delete_admin = $this->auth->id;
            $info->delete_why = $delete_why_info['id'];
        }

        // 启动事务
        Db::startTrans();
        try
        {
            if($delete_type == 2)
            {
                $info->delete();
            }
            else
            {
                $info->save();
            }

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('删除线索失败');
        }

        $this->success('删除线索成功','');
    }

    /**
     * 批量删除线索
     *
     * @ApiTitle    批量删除线索

     * @ApiParams (name="student_id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="delete_why", type="integer", required=false, description="删除原因")
     * @ApiParams (name="delete_type", type="integer", required=false, description="删除方式【1=进入回收站，2=彻底删除】")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657964522",
          "data": [
            {
              "createtime": "2022-06-08 11:17:59",//记录时间
              "operation_user": "思明校区",//操作人
              "content": "测试评价",//评价
              "from": "teacher"//self来自自己，teacher来自老师
            },
            ......
          ]
        })
     */
    public function delClueBatch()
    {
        #允许传入的参数
        $auth_params = ['student_id','delete_why','delete_type'];
        $param = $this->AuthParams($auth_params);

        $student_id = $this->request->param('student_id');
        $delete_why = intval($this->request->param('delete_why'));
        $delete_type = intval($this->request->param('delete_type'));

        if(empty($student_ids))
        {
            $this->error('请选择要删除的线索');
        }

        $student_ids = explode(',', $student_ids);

        $list = UserModel::where('id','in',$student_ids)->select();

        if(empty($list))
        {
            $this->error('请选择要删除的线索');
        }

        $delete = [];
        $update = [];
        foreach ($list as $key => $info) 
        {
            if($delete_type == 1 && $info['delete_admin'] > 0)
            {
                $this->error('线索已进入回收站');
            }

            if($info['follow_uid'] > 0 && $info['follow_uid'] != $this->auth->id)
            {
                $this->error('你不是线索'.$info['truename'].'【ID'.$info['id'].'】的跟进人,无法执行删除操作');
            }
            else if($info['follow_uid'] != $this->auth->id && $info['create_admin'] != $this->auth->id)
            {
                $this->error('你不是线索'.$info['truename'].'【ID'.$info['id'].'】的跟进人或创建人,无法执行删除操作');
            }
            else if($info['student_type'] == 3)
            {
                $this->error('线索'.$info['truename'].'【ID'.$info['id'].'】为历史线索,无法执行删除操作');
            }

            if($delete_type != 2)
            {
                if(empty($delete_why))
                {
                    $this->error('请选择删除原因');
                }

                $delete_why_info = TypeModel::where(['id' => $delete_why,'type' => 'delwhy'])->find();
                if(empty($delete_why_info))
                {
                    $this->error('请选择删除原因');
                }

                $update[] = ['id' => $info['id'],'deletetime' => time(),'delete_admin' => $this->auth->id,'delete_why' => $delete_why_info['id']];
            }
            else
            {
                $delete[] = $info['id'];
            }
        }

        // 启动事务
        Db::startTrans();
        try
        {
            if($delete_type == 2 && !empty($delete))
            {
                UserModel::destroy($delete);
            }
            else if(!empty($update))
            {
                $userModel = new UserModel;
                $userModel->saveAll($update);
            }
            else
            {
                $this->error('删除线索失败');
            }

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('删除线索失败');
        }

        $this->success('删除线索成功','');
    }

    /**
     * 全部线索
     *
     * @ApiTitle    全部线索
     * @ApiMethod   (GET)
    
     * @ApiParams (name="page_num", type="integer", required=false, description="页码【从1开始】")
     * @ApiParams (name="page_count", type="integer", required=false, description="每页数据数【默认10】")
     * @ApiParams (name="search_key", type="string", required=false, description="搜索关键字【姓名/手机号】")
     * @ApiParams (name="follow_status", type="integer", required=false, description="跟进状态:0=未分配,1=待认领,2=待跟进,3=跟进中,4=已成交")
     * @ApiParams (name="follow_stage", type="integer", required=false, description="跟进阶段:1=建立联系,2=确认意向,3=承诺到访,4=预约试听,5=完成试听,6=完成缴费")
     * @ApiParams (name="course_consultant", type="integer", required=false, description="课程顾问【ID】")
     * @ApiParams (name="lastfollow_time_start", type="string", required=false, description="最后跟进时间起始")
     * @ApiParams (name="lastfollow_time_end", type="string", required=false, description="最后跟进时间结束")
     * @ApiParams (name="students_source", type="string", required=true,description="学员来源【ID号，多项以,分隔】")
     * @ApiParams (name="consult_course", type="string",required=false,description="咨询课程【ID号，多项以,分隔】")
     * @ApiParams (name="collect_people", type="integer", required=true, description="采单人【ID】")
     * @ApiParams (name="label", type="string", required=true, description="标签【多项以,分隔】")
     * @ApiParams (name="intention_level", type="integer", required=true,description="意向级别:1=低,2=中,3=高")
     * @ApiParams (name="create_time_start", type="string", required=false, description="创建时间起始")
     * @ApiParams (name="create_time_end", type="string", required=false, description="创建时间结束")
     * @ApiParams (name="nextfollow_time_start", type="string", required=false, description="下次跟进时间起始")
     * @ApiParams (name="nextfollow_time_end", type="string", required=false, description="下次跟进时间结束")
     * @ApiParams (name="age_year_min", type="integer", required=false,description="最小年龄")
     * @ApiParams (name="age_year_max", type="integer", required=false,description="最大年龄")
     * @ApiParams (name="gender", type="integer", required=false,description="性别:0=未知,1=男,2=女")
     * @ApiParams (name="student_type", type="integer", required=false,description="是否在读:0=无,1=在读")
     * @ApiParams (name="is_follow", type="integer", required=false,description="跟进状态:0=全部,1=有跟进人,2=无跟进人")
     * @ApiParams (name="quick", type="integer", required=false,description="快捷筛选:0=全部,1=今日待跟进,2=7天未跟进,3=30天未转化,4=今日新增,5=本周新增,6=本月新增,7=本年新增")

     * @ApiSector   销售中心
     * @ApiReturn   ({
        'code' : '1',
        'msg' : '返回成功',
        'time' : '1657378506',
        'data' : [{...}]
     * })
     */
    public function allClue()
    {
        #允许传入的参数
        $auth_params = ['clue_type','page_num','page_count','search_key','follow_status','follow_stage','course_consultant','lastfollow_time_start','lastfollow_time_end','students_source','consult_course','collect_people','label','intention_level','create_time_start','create_time_end','nextfollow_time_start','nextfollow_time_end','age_year_min','age_year_max','gender','student_type','is_follow','quick'];
        $param = $this->AuthParams($auth_params);

        $page_num = empty($param['page_num']) ? 1 : intval($param['page_num']);
        $page_count = empty($param['page_count']) ? 10 : intval($param['page_count']);

        $map1 = [];
        $map1['a.delete_admin'] = 0;
        $map1['a.shop_id'] = $this->auth->shop_id;

        $is_follow = !empty($param['is_follow']) ? intval($param['is_follow']) : 0;
        if($is_follow == 1)
        {
            $map1['a.follow_uid'] = ['>',0];
        }
        else if($is_follow == 2)
        {
            $map1['a.follow_uid'] = 0;
        }

        $quick = !empty($param['quick']) ? intval($param['quick']) : 0;
        if($quick)

        #搜索关键字【姓名/手机号】
        if(!empty($param['search_key']))
        {
            $map1['a.truename'] = ['like',"%{$param['search_key']}%"];
            $map1['a.standby_contact'] = ['like',"%{$param['search_key']}%"];
            $map1['a.mobile'] = ['like',"%{$param['search_key']}%"];
        }

        $map2 = [];

        $this->clueScreen($param,$map2);

        #查询线索数据总数
        $clue_count = UserModel::alias('a')->where($map2)->where(function($query) use ($map1){
            if(!empty($map1))
            {
                $query->whereOr($map1);
            }
        })->count();

        if($clue_count <= 0)
        {
            $this->success('获取数据成功','',[]);
        }

        #最大页码
        $max_page_num = bcdiv($clue_count,$page_count);
        if($clue_count % $page_count > 0)
        {
            $max_page_num++;
        }

        if($page_num < 0)
        {
            $this->error('已经是第一页了');
        }

        if($page_num > $max_page_num)
        {
            $this->error('已经是最后一页了');
        }

        $limit_start_num = bcmul(bcsub($page_num,1),$page_count);

        $list = UserModel::field('a.truename,b.truename as consultant_name,a.students_source,a.lastfollow_time,a.follow_status,a.intention_level,c.username as delete_user,d.username as follow_user')
        ->alias('a')
        ->join('ss_campus_clew_consultant b','a.course_consultant = b.id','left')
        ->join('ss_manystore c','a.delete_admin = c.id','left')
        ->join('ss_manystore d','d.id = a.follow_uid','left')
        ->where($map2)
        ->where(function($query) use ($map1){$query->whereOr($map1);})
        ->limit($limit_start_num,$page_count)
        ->select();

        $data = [];

        foreach ($list as & $value)
        {
            if(!empty($value['students_source']))
            {
                $students_source_list = TypeModel::where('id','in',$value['students_source'])->select();
                $students_source = [];
                foreach ($students_source_list as $v)
                {
                    $students_source[] = $v['name'];
                }
                $value['students_source'] = implode(',', $students_source);
            }
            else
            {
                $value['students_source'] = '';
            }

            $data[] = [
                'name' => $value['truename'],//学员名称
                'consultant_name' => $value['consultant_name'],//顾问名称
                'students_source' => $value['students_source'],//学生来源
                'lastfollow_time' => date('Y-m-d H:i:s',$value['lastfollow_time']),//最后跟进时间
                'follow_status' => $value['follow_status'],//跟进状态
                'intention_level' => intval($value['intention_level']),//意向级别
                'follow_user' => $value['follow_user'],//跟进人
            ];    
        }
        
        $this->success('获取数据成功','',$data);
    }

    /**
     * 我的线索
     *
     * @ApiTitle    我的线索
     * @ApiMethod   (GET)
    
     * @ApiParams (name="page_num", type="integer", required=false, description="页码【从1开始】")
     * @ApiParams (name="page_count", type="integer", required=false, description="每页数据数【默认10】")
     * @ApiParams (name="search_key", type="string", required=false, description="搜索关键字【姓名/手机号】")
     * @ApiParams (name="follow_status", type="integer", required=false, description="跟进状态:0=未分配,1=待认领,2=待跟进,3=跟进中,4=已成交")
     * @ApiParams (name="follow_stage", type="integer", required=false, description="跟进阶段:1=建立联系,2=确认意向,3=承诺到访,4=预约试听,5=完成试听,6=完成缴费")
     * @ApiParams (name="course_consultant", type="integer", required=false, description="课程顾问【ID】")
     * @ApiParams (name="lastfollow_time_start", type="string", required=false, description="最后跟进时间起始")
     * @ApiParams (name="lastfollow_time_end", type="string", required=false, description="最后跟进时间结束")
     * @ApiParams (name="students_source", type="string", required=true,description="学员来源【ID号，多项以,分隔】")
     * @ApiParams (name="consult_course", type="string",required=false,description="咨询课程【ID号，多项以,分隔】")
     * @ApiParams (name="collect_people", type="integer", required=true, description="采单人【ID】")
     * @ApiParams (name="label", type="string", required=true, description="标签【多项以,分隔】")
     * @ApiParams (name="intention_level", type="integer", required=true,description="意向级别:1=低,2=中,3=高")
     * @ApiParams (name="create_time_start", type="string", required=false, description="创建时间起始")
     * @ApiParams (name="create_time_end", type="string", required=false, description="创建时间结束")
     * @ApiParams (name="nextfollow_time_start", type="string", required=false, description="下次跟进时间起始")
     * @ApiParams (name="nextfollow_time_end", type="string", required=false, description="下次跟进时间结束")
     * @ApiParams (name="age_year_min", type="integer", required=false,description="最小年龄")
     * @ApiParams (name="age_year_max", type="integer", required=false,description="最大年龄")
     * @ApiParams (name="gender", type="integer", required=false,description="性别:0=未知,1=男,2=女")
     * @ApiParams (name="student_type", type="integer", required=false,description="是否在读:0=无,1=在读")

     * @ApiSector   销售中心
     * @ApiReturn   ({
        'code' : '1',
        'msg' : '返回成功',
        'time' : '1657378506',
        'data' : [{...}]
     * })
     */
    public function myClue()
    {
        #允许传入的参数
        $auth_params = ['clue_type','page_num','page_count','search_key','follow_status','follow_stage','course_consultant','lastfollow_time_start','lastfollow_time_end','students_source','consult_course','collect_people','label','intention_level','create_time_start','create_time_end','nextfollow_time_start','nextfollow_time_end','age_year_min','age_year_max','gender','student_type'];
        $param = $this->AuthParams($auth_params);

        $page_num = empty($param['page_num']) ? 1 : intval($param['page_num']);
        $page_count = empty($param['page_count']) ? 10 : intval($param['page_count']);

        $map1 = [];
        $map1['a.delete_admin'] = 'null';
        $map1['a.follow_uid'] = $this->auth->id;

        #搜索关键字【姓名/手机号】
        if(!empty($param['search_key']))
        {
            $map1['a.truename'] = ['like',"%{$param['search_key']}%"];
            $map1['a.standby_contact'] = ['like',"%{$param['search_key']}%"];
            $map1['a.mobile'] = ['like',"%{$param['search_key']}%"];
        }

        $map2 = [];

        $this->clueScreen($param,$map2);

        #查询线索数据总数
        $clue_count = UserModel::alias('a')->where($map2)->where(function($query) use ($map1){
            if(!empty($map1))
            {
                $query->whereOr($map1);
            }
        })->count();

        if($clue_count <= 0)
        {
            $this->success('获取数据成功','',[]);
        }

        #最大页码
        $max_page_num = bcdiv($clue_count,$page_count);
        if($clue_count % $page_count > 0)
        {
            $max_page_num++;
        }

        if($page_num < 0)
        {
            $this->error('已经是第一页了');
        }

        if($page_num > $max_page_num)
        {
            $this->error('已经是最后一页了');
        }

        $limit_start_num = bcmul(bcsub($page_num,1),$page_count);

        $list = UserModel::field('a.truename,b.truename as consultant_name,a.students_source,a.lastfollow_time,a.follow_status,a.intention_level,c.username as delete_user')
        ->alias('a')
        ->join('ss_campus_clew_consultant b','a.course_consultant = b.id','left')
        ->join('ss_manystore c','a.delete_admin = c.id','left')
        ->where($map2)
        ->where(function($query) use ($map1){$query->whereOr($map1);})
        ->limit($limit_start_num,$page_count)
        ->select();

        $data = [];

        foreach ($list as & $value)
        {
            if(!empty($value['students_source']))
            {
                $students_source_list = TypeModel::where('id','in',$value['students_source'])->select();
                $students_source = [];
                foreach ($students_source_list as $v)
                {
                    $students_source[] = $v['name'];
                }
                $value['students_source'] = implode(',', $students_source);
            }
            else
            {
                $value['students_source'] = '';
            }

            $data[] = [
                'name' => $value['truename'],//学员名称
                'consultant_name' => $value['consultant_name'],//顾问名称
                'students_source' => $value['students_source'],//学生来源
                'lastfollow_time' => date('Y-m-d H:i:s',$value['lastfollow_time']),//最后跟进时间
                'follow_status' => $value['follow_status'],//跟进状态
                'intention_level' => intval($value['intention_level']),//意向级别
            ];    
        }
        
        $this->success('获取数据成功','',$data);
    }

    /**
     * 公有池
     *
     * @ApiTitle    公有池
     * @ApiMethod   (GET)
    
     * @ApiParams (name="page_num", type="integer", required=false, description="页码【从1开始】")
     * @ApiParams (name="page_count", type="integer", required=false, description="每页数据数【默认10】")
     * @ApiParams (name="search_key", type="string", required=false, description="搜索关键字【姓名/手机号】")
     * @ApiParams (name="students_source", type="string", required=true,description="学员来源【ID号，多项以,分隔】")
     * @ApiParams (name="label", type="string", required=true, description="标签【多项以,分隔】")
     * @ApiParams (name="create_time_start", type="string", required=false, description="创建时间起始")
     * @ApiParams (name="create_time_end", type="string", required=false, description="创建时间结束")
     * @ApiParams (name="age_year_min", type="integer", required=false,description="最小年龄")
     * @ApiParams (name="age_year_max", type="integer", required=false,description="最大年龄")
     * @ApiParams (name="gender", type="integer", required=false,description="性别:0=未知,1=男,2=女")
     * @ApiParams (name="school", type="integer", required=false,description="学校名称")

     * @ApiSector   销售中心
     * @ApiReturn   ({
        'code' : '1',
        'msg' : '返回成功',
        'time' : '1657378506',
        'data' : [{...}]
     * })
     */
    public function publicPool()
    {
        #允许传入的参数
        $auth_params = ['page_num','page_count','search_key','students_source','label','create_time_start','create_time_end','age_year_min','age_year_max','gender','school'];
        $param = $this->AuthParams($auth_params);

        $page_num = empty($param['page_num']) ? 1 : intval($param['page_num']);
        $page_count = empty($param['page_count']) ? 10 : intval($param['page_count']);

        $map1 = [];
        $map1['a.is_publicpool'] = 1;
        $map1['a.delete_admin'] = 'null';
        #搜索关键字【姓名/手机号】
        if(!empty($param['search_key']))
        {
            $map1['a.truename'] = ['like',"%{$param['search_key']}%"];
            $map1['a.standby_contact'] = ['like',"%{$param['search_key']}%"];
            $map1['a.mobile'] = ['like',"%{$param['search_key']}%"];
        }

        $map2 = [];

        $this->clueScreen($param,$map2);

        #查询线索数据总数
        $clue_count = UserModel::alias('a')->where($map2)->where(function($query) use ($map1){
            if(!empty($map1))
            {
                $query->whereOr($map1);
            }
        })->count();

        if($clue_count <= 0)
        {
            $this->success('获取数据成功','',[]);
        }

        #最大页码
        $max_page_num = bcdiv($clue_count,$page_count);
        if($clue_count % $page_count > 0)
        {
            $max_page_num++;
        }

        if($page_num < 0)
        {
            $this->error('已经是第一页了');
        }

        if($page_num > $max_page_num)
        {
            $this->error('已经是最后一页了');
        }

        $limit_start_num = bcmul(bcsub($page_num,1),$page_count);

        $list = UserModel::field('a.truename,a.students_source,a.lastfollow_time,a.follow_status,a.intention_level,s.name as school_name')
        ->alias('a')
        ->join('ss_manystore_shop s','a.shop_id = s.id','left')
        ->where($map2)
        ->where(function($query) use ($map1){$query->whereOr($map1);})
        ->limit($limit_start_num,$page_count)
        ->select();

        $data = [];

        foreach ($list as & $value)
        {
            if(!empty($value['students_source']))
            {
                $students_source_list = TypeModel::where('id','in',$value['students_source'])->select();
                $students_source = [];
                foreach ($students_source_list as $v)
                {
                    $students_source[] = $v['name'];
                }
                $value['students_source'] = implode(',', $students_source);
            }
            else
            {
                $value['students_source'] = '';
            }

            $data[] = [
                'name' => $value['truename'],//学员名称
                'students_source' => $value['students_source'],//学生来源
                'create_time' => date('Y-m-d H:i:s',$value['createtime']),//创建时间
                'school_name' => $value['school_name'],//校区
            ];    
        }
        
        $this->success('获取数据成功','',$data);
    }

    /**
     * 回收站
     *
     * @ApiTitle    回收站
     * @ApiMethod   (GET)
    
     * @ApiParams (name="page_num", type="integer", required=false, description="页码【从1开始】")
     * @ApiParams (name="page_count", type="integer", required=false, description="每页数据数【默认10】")
     * @ApiParams (name="search_key", type="string", required=false, description="搜索关键字【姓名/手机号】")
     * @ApiParams (name="intention_level", type="string", required=true,description="意向级别")
     * @ApiParams (name="student_type", type="integer", required=false,description="学员类型:0=线索,3=历史")

     * @ApiParams (name="delete_admin", type="integer", required=true, description="删除者【ID】")
     * @ApiParams (name="delete_why", type="string", required=true, description="删除原因【ID】")
     
     * @ApiParams (name="create_time_start", type="string", required=false, description="创建时间起始")
     * @ApiParams (name="create_time_end", type="string", required=false, description="创建时间结束")
     * @ApiParams (name="delete_time_start", type="string", required=false, description="删除时间起始")
     * @ApiParams (name="delete_time_end", type="string", required=false, description="删除时间结束")
     

     * @ApiSector   销售中心
     * @ApiReturn   ({
        'code' : '1',
        'msg' : '返回成功',
        'time' : '1657378506',
        'data' : [{
          "code": 1,
          "msg": "获取数据成功",
          "time": "1657956062",
          "data": [
            {
              "name": "张晓曦",//学员姓名
              "students_source": 0,//学员来源
              "delete_user": "shensou",删除者
              "delete_why": "空号/错号"//删除原因
            },
            ......
          ]
        }]
     * })
     */
    public function recycleBin()
    {
        #允许传入的参数
        $auth_params = ['page_num','page_count','search_key','intention_level','student_type','create_time_start','create_time_end','delete_time_start','delete_time_end','delete_admin','delete_why'];
        $param = $this->AuthParams($auth_params);

        $page_num = empty($param['page_num']) ? 1 : intval($param['page_num']);
        $page_count = empty($param['page_count']) ? 10 : intval($param['page_count']);

        $map1 = [];
        $map1['a.delete_admin'] = ['>',0];
        $map1['a.shop_id'] = $this->auth->shop_id;

        #搜索关键字【姓名/手机号】
        if(!empty($param['search_key']))
        {
            $map1['a.truename'] = ['like',"%{$param['search_key']}%"];
            $map1['a.standby_contact'] = ['like',"%{$param['search_key']}%"];
            $map1['a.mobile'] = ['like',"%{$param['search_key']}%"];
        }

        $map2 = [];

        $this->clueScreen($param,$map2);

        #查询线索数据总数
        $clue_count = UserModel::alias('a')->where($map2)->where(function($query) use ($map1){
            if(!empty($map1))
            {
                $query->whereOr($map1);
            }
        })->count();

        if($clue_count <= 0)
        {
            $this->success('获取数据成功','',[]);
        }

        #最大页码
        $max_page_num = bcdiv($clue_count,$page_count);
        if($clue_count % $page_count > 0)
        {
            $max_page_num++;
        }

        if($page_num < 0)
        {
            $this->error('已经是第一页了');
        }

        if($page_num > $max_page_num)
        {
            $this->error('已经是最后一页了');
        }

        $limit_start_num = bcmul(bcsub($page_num,1),$page_count);

        $list = UserModel::field('a.truename,a.intention_level,m.username as delete_user,t.name as delete_why')
        ->alias('a')
        ->join('ss_manystore m','a.delete_admin = m.id','left')
        ->join('ss_type t','a.delete_why = t.id','left')
        ->where($map2)
        ->where(function($query) use ($map1){$query->whereOr($map1);})
        ->limit($limit_start_num,$page_count)
        ->select();

        $data = [];

        foreach ($list as & $value)
        {
            $data[] = [
                'name' => $value['truename'],//学员名称
                'intention_level' => intval($value['intention_level']),//意向等级
                'delete_user' => $value['delete_user'],//删除人
                'delete_why' => $value['delete_why'],//删除原因
            ];    
        }
        
        $this->success('获取数据成功','',$data);
    }

     /**
     * 线索筛选
     *
     * @ApiTitle    线索筛选

     * @ApiParams (name="param", type="integer", required=false, description="筛选的参数")
     * @ApiParams (name="map1", type="integer", required=false, description="条件")
     */
    private function clueScreen(&$param,&$map)
    {
        #跟进状态:0=未分配,1=待认领,2=待跟进,3=跟进中,4=已成交
        if(isset($param['follow_status']) && $param['follow_status'] != '' && $param['follow_status'] >= 0 && $param['follow_status'] <= 4)
        {
            $map['a.follow_status'] = $param['follow_status'];
        }

        #跟进阶段:1=建立联系,2=确认意向,3=承诺到访,4=预约试听,5=完成试听,6=完成缴费
        if(isset($param['follow_stage']) && $param['follow_stage'] != '' && $param['follow_stage'] >= 1 && $param['follow_stage'] <= 6)
        {
            $map['a.follow_stage'] = $param['follow_stage'];
        }

        #课程顾问【ID】
        if(!empty($param['course_consultant']))
        {
            $param['course_consultant'] = intval($param['course_consultant']);
            $map['a.course_consultant'] = $param['course_consultant'];
        }

        #最后跟进时间
        $lastfollow_time_start = !empty($param['lastfollow_time_start']) ? strtotime($param['lastfollow_time_start'].'00:00:00') : 0;
        $lastfollow_time_end = !empty($param['lastfollow_time_end']) ? strtotime($param['lastfollow_time_end'].'23:59:59') : 0;

        if($lastfollow_time_start > 0 && $lastfollow_time_end > 0)
        {
            $map['a.lastfollow_time'] = ['BETWEEN',[$lastfollow_time_start,$lastfollow_time_end]];
        }
        else if($lastfollow_time_start > 0)
        {
            $map['a.lastfollow_time'] = ['>=',$lastfollow_time_start];
        }
        else if($lastfollow_time_end > 0)
        {
            $map['a.lastfollow_time'] = ['<=',$lastfollow_time_end];
        }

        #下次跟进时间
        $nextfollow_time_start = !empty($param['nextfollow_time_start']) ? strtotime($param['nextfollow_time_start'].'00:00:00') : 0;
        $nextfollow_time_end = !empty($param['nextfollow_time_end']) ? strtotime($param['nextfollow_time_end'].'23:59:59') : 0;

        if($nextfollow_time_start > 0 && $nextfollow_time_end > 0)
        {
            $map['a.nextfollow_time'] = ['BETWEEN',[$nextfollow_time_start,$nextfollow_time_end]];
        }
        else if($nextfollow_time_start > 0)
        {
            $map['a.nextfollow_time'] = ['>=',$nextfollow_time_start];
        }
        else if($nextfollow_time_end > 0)
        {
            $map['a.nextfollow_time'] = ['<=',$nextfollow_time_end];
        }

        #创建时间
        $create_time_start = !empty($param['create_time_start']) ? strtotime($param['create_time_start'].'00:00:00') : 0;
        $create_time_end = !empty($param['create_time_end']) ? strtotime($param['create_time_end'].'23:59:59') : 0;

        if($create_time_start > 0 && $create_time_end > 0)
        {
            $map['a.createtime'] = ['BETWEEN',[$create_time_start,$create_time_end]];
        }
        else if($create_time_start > 0)
        {
            $map['a.createtime'] = ['>=',$create_time_start];
        }
        else if($create_time_end > 0)
        {
            $map['a.createtime'] = ['<=',$create_time_end];
        }

        #删除时间
        $delete_time_start = !empty($param['delete_time_start']) ? strtotime($param['delete_time_start'].'00:00:00') : 0;
        $delete_time_end = !empty($param['delete_time_end']) ? strtotime($param['delete_time_end'].'23:59:59') : 0;

        if($delete_time_start > 0 && $delete_time_end > 0)
        {
            $map['a.deletetime'] = ['BETWEEN',[$delete_time_start,$delete_time_end]];
        }
        else if($delete_time_start > 0)
        {
            $map['a.deletetime'] = ['>=',$delete_time_start];
        }
        else if($delete_time_end > 0)
        {
            $map['a.deletetime'] = ['<=',$delete_time_end];
        }



        if(!empty($param['students_source']))
        {
            $param['students_source'] = explode(',', $param['students_source']);
            $tmp = [];

            foreach ($param['students_source'] as $key => $value)
            {
                $value = intval($value);
                $tmp[] = ['like','%,'.$value.',%'];
                $tmp[] = ['like','%,'.$value];
                $tmp[] = ['like',$value.',%'];
                $tmp[] = $value;
            }
            $tmp[] = 'or';

            $map['a.students_source'] = $tmp;
        }

        if(!empty($param['consult_course']))
        {
            $param['consult_course'] = explode(',', $param['consult_course']);
            $tmp = [];

            foreach ($param['consult_course'] as $key => $value)
            {
                $value = intval($value);
                $tmp[] = ['like','%,'.$value.',%'];
                $tmp[] = ['like','%,'.$value];
                $tmp[] = ['like',$value.',%'];
                $tmp[] = $value;
            }
            $tmp[] = 'or';

            $map['a.consult_course'] = $tmp;
        }

        if(!empty($param['collect_people']))
        {
            $param['collect_people'] = explode(',', $param['collect_people']);
            $tmp = [];

            foreach ($param['collect_people'] as $key => $value)
            {
                $value = intval($value);
                $tmp[] = ['like','%,'.$value.',%'];
                $tmp[] = ['like','%,'.$value];
                $tmp[] = ['like',$value.',%'];
                $tmp[] = $value;
            }
            $tmp[] = 'or';

            $map['a.collect_people'] = $tmp;
        }

        if(!empty($param['label']))
        {
            $param['label'] = explode(',', $param['label']);
            $tmp = [];

            foreach ($param['label'] as $key => $value)
            {
                $value = intval($value);
                $tmp[] = ['like','%,'.$value.',%'];
                $tmp[] = ['like','%,'.$value];
                $tmp[] = ['like',$value.',%'];
                $tmp[] = $value;
            }
            $tmp[] = 'or';

            $map['a.label'] = $tmp;
        }

        if(isset($param['intention_level']))
        {
            $map['a.intention_level'] = intval($param['intention_level']);
        }

        if(isset($param['age_year_min']) && isset($param['age_year_max']))
        {
            $map['a.age_year'] = ['between',[intval($param['age_year_min']),intval($param['age_year_max'])]];
        }
        else if(isset($param['age_year_min']))
        {
            $map['a.age_year'] = ['>=',intval($param['age_year_min'])];
        }
        else if(isset($param['age_year_max']))
        {
            $map['a.age_year'] = ['<=',intval($param['age_year_max'])];
        }

        if(isset($param['gender']))
        {
            $map['a.gender'] = intval($param['gender']);
        }

        if(isset($param['student_type']))
        {
            $map['a.student_type'] = intval($param['student_type']);
        }

        if(!empty($param['school']))
        {
            $map['s.name'] = ['like','%'.$param['school'].'%'];
        }

        if(!empty($param['delete_why']))
        {
            $map['a.delete_why'] = intval($param['delete_why']);
        }

        if(!empty($param['delete_admin']))
        {
            $map['a.delete_admin'] = intval($param['delete_why']);
        }
    }

     /**
     * 线索详情
     *
     * @ApiTitle    线索详情

     * @ApiParams (name="id", type="integer", required=false, description="学员ID")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "获取数据成功",
          "time": "1658037788",
          "data": {
            "avatar": "/uploads/20220710/6c30a87c415fc011fbdb73978ba43571.jpg",//头像路径
            "truename": "新测试",//线索姓名
            "mobile_identity": 0,//谁的手机号:0=无,1=本人,2=妈妈,3=爸爸,4-爷爷,5=奶奶,6=外公,7=外婆
            "mobile": "",//手机号
            "gender": 1,//性别:0=未知,1=男,2=女
            "age_year": 10,//年龄(几岁)
            "age_month": 2,//年龄(几个月)
            "birthday": '2022-07-15',//生日
            "standby_contact": "",//备用手机号
            "standbycontact_identity": 0,//谁的备用号码:0=无,1=本人,2=妈妈,3=爸爸,4-爷爷,5=奶奶,6=外公,7=外婆
            "remark": "阿斯达岁的萨多啥多啥",//备注
            "label": "有潜力",//标签
            "students_source": "地推",//来源
            "collect_people": "服务商",//采单人
            "course_consultant": "小天"//课程顾问
          }
        })
     */
    public function getClueInfo()
    {
        $id = intval($this->request->param('id'));

        $info = UserModel::field('a.avatar,a.truename,a.mobile_identity,a.mobile,a.gender,a.age_year,a.age_month,a.birthday,a.standby_contact,a.standbycontact_identity,a.remark,a.label,a.students_source,m.username as collect_people,c.truename as course_consultant')
        ->alias('a')
        ->join('ss_campus_clew_consultant c','c.id = a.course_consultant','left')
        ->join('ss_manystore m','m.id = a.collect_people','left')
        // ->join('ss_type t','t1.id = a.label','left')
        ->where(['a.id' => $id])
        // ->fetchSql()
        ->find();

        if(!empty($info['students_source']))
        {
            $students_source_list = TypeModel::where('id','in',$info['students_source'])->select();
            $students_source = [];
            foreach ($students_source_list as $v)
            {
                $students_source[] = $v['name'];
            }
            $info['students_source'] = implode(',', $students_source);
        }
        else
        {
            $info['students_source'] = '';
        }

        if(!empty($info['label']))
        {
            $label_list = TypeModel::where('id','in',$info['label'])->select();
            $label = [];
            foreach ($label_list as $v)
            {
                $label[] = $v['name'];
            }
            $info['label'] = implode(',', $label);
        }
        else
        {
            $info['label'] = '';
        }

        if(empty($info))
        {
            $this->error('线索不存在');
        }

        $this->success('获取数据成功','',$info);
    }

    /**
     * 添加档案
     *
     * @ApiTitle    添加档案

     * @ApiParams (name="relation_id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="type_id", type="integer", required=false, description="档案类型")
     * @ApiParams (name="to_student", type="integer", required=false, description="是否推送给学员:0=否,1=是")
     * @ApiParams (name="to_app", type="integer", required=false, description="是否推送到app:0=否,1=是")
     * @ApiParams (name="content", type="string", required=false, description="内容")
     * @ApiParams (name="images", type="json", required=false, description="图片【文件上传API接口返回参数url及说明文字，实例[{\"name\":\"示例',\"file\":\"/upload/202220701/a.jpg\"},......]】")
     * @ApiParams (name="video", type="json", required=false, description="视频【同图片】")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "添加档案成功",
          "time": "1657984618",
          "data": null
        })
     */
    public function CreateGrowthPortfolio()
    {
        #允许传入的参数
        $auth_params = ['relation_id','type_id','to_student','to_app','content','images','video','images_text','video_text'];
        $param = $this->AuthParams($auth_params);

        $info = UserModel::field('a.id,a.truename,a.follow_uid,a.shop_id')
        ->alias('a')
        ->where(['a.id' => $param['relation_id']])
        // ->fetchSql()
        ->find();

        if(empty($info))
        {
            $this->error('线索不存在');
        }

        if($info['follow_uid'] != $this->auth->id && $this->auth->level != 0)
        {
            $this->error('你不是该线索的跟进人');
        }

        $param['operation_id'] = $info['follow_uid'];
        $param['shop_id'] = $info['shop_id'];
        $param['style'] = 2;

        $type_info = TypeModel::where(['id' => $param['type_id'],'type' => 'growth'])->find();
        if(empty($type_info))
        {
            $this->error('请选择档案类型');
        }

        $param['to_student'] = empty($param['to_student']) ? 0 : 1;
        $param['to_app'] = empty($param['to_app']) ? 0 : 1;

        if(!empty($param['images']))
        {
            $images = json_decode(html_entity_decode($param['images']),true);

            $re_images = [];
            foreach ($images as $key => $value)
            {
                if(!is_file('.'.$value['file']))
                {
                    $this->error('请上传图片');
                }

                $re_images[] = [
                    'name' => !empty($value['name']) ? $value['name'] : '',
                    'file' => $value['file'],
                ];
            }
            $param['images'] = json_encode($re_images);
        }

        if(!empty($param['video']))
        {
            $video = json_decode(html_entity_decode($param['video']),true);
            $re_video = [];
            foreach ($video as $key => $value)
            {
                if(!is_file('.'.$value['file']))
                {
                    $this->error('请上传图片');
                }

                $re_video[] = [
                    'name' => !empty($value['name']) ? $value['name'] : '',
                    'file' => $value['file'],
                ];
            }
            $param['video'] = json_encode($re_video);
        }

        $param['createtime'] = time();

        // 启动事务
        Db::startTrans();
        try
        {
            $growthPortfolioModel = new GrowthPortfolioModel;
            $growthPortfolioModel->save($param);

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('添加档案失败');
        }

        $this->success('添加档案成功','');
    }

    

    /**
     * 线索类型转换
     *
     * @ApiTitle    线索类型转换

     * @ApiParams (name="clew_id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="type", type="integer", required=false, description="转换类型:0=线索,1=试听,2=在读,3=历史")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "更改线索类型成功",
          "time": "1657996652",
          "data": null
        })
     */
    public function AuditionClues()
    {
        #允许传入的参数
        $clew_id = intval($this->request->param('clew_id'));
        $type = intval($this->request->param('type'));

        $info = UserModel::get($clew_id);

        if(empty($info))
        {
            $this->error('线索不存在');
        }

        if($info->follow_uid != $this->auth->id && ($this->auth->level == 1 && $info->shop_id != $this->auth->shop_id))
        {
            $this->error('你不是该线索的跟进人或校区负责人,无权操作');
        }

        if($info->student_type > 0 && empty($info->follow_uid))
        {
            $this->error('操作失败，当前线索没有跟进人');
        }

        if($type == 3)
        {
            //转换为历史学员时移除所在班级、购买的课程全部结课
            CampusClassStudent::where(['user_id' => $clew_id])->save(['is_stop' => 1]);
            //取消约课中的记录
            CampusClassDateRecord::where(['user_id' => $clew_id,'status' => ['<>',2]])->save(['status' => 2]);
            //取消购买的课程
            CampusCourseOrderSublevel::where(['user_id' => $clew_id,'type' => 3,'status' => 1])->save(['status' => 0]);
            //取消跟进记录
            CampusFollowModel::where(['clew_id' => $clew_id])->save(['task_status' => 1,'cancel_time' => time(),'cancel_why' => '转为历史学员']);
        }

        // 启动事务
        Db::startTrans();
        try
        {
            $info->student_type = $type;
            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('更改线索类型失败');
        }

        $this->success('更改线索类型成功','');
    }

    /**
     * 分配线索
     *
     * @ApiTitle    分配线索

     * @ApiParams (name="clew_id", type="integer", required=false, description="学员ID")
     * @ApiParams (name="type", type="integer", required=false, description="分配方式【-1：回收线索,=0:公有池，>0:指定人】")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "更改线索为试听成功",
          "time": "1657996652",
          "data": null
        })
     */
    public function distributionClues()
    {
        $clew_id = intval($this->request->param('clew_id'));
        $type = intval($this->request->param('type'));

        $info = UserModel::get($clew_id);

        if(empty($info))
        {
            $this->error('线索不存在');
        }

        if(!empty($info->follow_status))
        {
            $this->error('该线索当前不可分配');
        }

        if($this->auth->shop_id > 0 && $info->is_publicpool = 0)
        {
            if($info->follow_uid != $this->auth->id && ($this->auth->level == 1 && $info->shop_id != $this->auth->shop_id))
            {
                $this->error('你不是该线索的跟进人或校区负责人,无权操作');
            }
        }

        if($type > 0)
        {
            $manystore = ManystoreModel::get($type);
            if(empty($manystore))
            {
                $this->error('分配人员不存在');
            }

            if($manystore->shop_id != $this->auth->shop_id)
            {
                $this->error('分配人员不是本校区');
            }

            if($manystore->level <= $this->auth->level)
            {
                $this->error('没有权限为该人员分配线索');
            }

            $info->is_publicpool = 0;
            $info->follow_status = 3;
            $info->follow_uid = $manystore->id;
            $info->shop_id = $manystore->shop_id;
        }
        else if($type == -1)
        {
            $info->is_publicpool = 0;
            $info->follow_status = 0;
            $info->follow_uid = 0;
        }
        else
        {
            $info->is_publicpool = 1;
            $info->publicpool_time = time();
            $info->follow_status = 0;
            $info->follow_uid = 0;
            $info->shop_id = 0;
        }

        // 启动事务
        Db::startTrans();
        try
        {
            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('分配失败');
        }

        $this->success('分配成功','');
    }

    /**
     * 批量分配线索
     *
     * @ApiTitle    批量分配线索

     * @ApiParams (name="clew_id", type="integer", required=false, description="学员ID【多项以逗号分隔】")
     * @ApiParams (name="type", type="integer", required=false, description="分配方式【-1：回收线索,=0:公有池，>0:指定人】")

     * @ApiSector   销售中心
     * @ApiReturn   ({
          "code": 1,
          "msg": "更改线索为试听成功",
          "time": "1657996652",
          "data": null
        })
     */
    public function distributionCluesBatch()
    {
        $clew_ids = $this->request->param('clew_id');
        $type = intval($this->request->param('type'));

        if(empty($clew_ids))
        {
            $this->error('请选择要分配的线索');
        }

        $clew_ids = explode(',', $clew_ids);

        $list = UserModel::where('id','in',$clew_ids)->select();

        if(empty($list))
        {
            $this->error('请选择要分配的线索');
        }

        if($type > 0)
        {
            //分配到指定人
            $manystore = ManystoreModel::get($type);
            if(empty($manystore))
            {
                $this->error('分配人员不存在');
            }

            if($manystore->shop_id != $this->auth->shop_id)
            {
                $this->error('分配人员不是本校区');
            }

            if($manystore->level <= $this->auth->level)
            {
                $this->error('没有权限为该人员分配线索');
            }
        }

        $update = [];

        foreach ($list as $key => $info)
        {
            if(!empty($info['follow_status']))
            {
                $this->error('线索'.$info['truename'].'【ID:'.$info['id'].'】当前状态不可分配');
            }

            if($this->auth->shop_id > 0 && $info['is_publicpool'] = 0)
            {
                if($info['follow_uid'] != $this->auth->id && ($this->auth->level == 1 && $info['shop_id'] != $this->auth->shop_id))
                {
                    $this->error('你不是线索'.$info['truename'].'【ID:'.$info['id'].'】的跟进人或校区负责人,无权操作');
                }
            }

            if($type > 0)
            {
                $update[] = ['id' => $info['id'],'is_publicpool' => 0,'follow_status' => 3,'follow_uid' => $manystore->id,'shop_id' => $manystore->shop_id];
            }
            else if($type == -1)
            {
                $update[] = ['id' => $info['id'],'is_publicpool' => 0,'follow_status' => 0,'follow_uid' => 0];
            }
            else
            {
                $update[] = ['id' => $info['id'],'is_publicpool' => 0,'follow_status' => 0,'follow_uid' => 0,'shop_id' => 0,'publicpool_time' => time()];
            }
        }

        // 启动事务
        Db::startTrans();
        try
        {
            $userModel = new userModel;
            $userModel->saveAll($update);

            $info->save();

            // 提交事务
            Db::commit();
        }
        catch (\Exception $e)
        {
            // 回滚事务
            Db::rollback();
            $this->error('批量分配失败');
        }

        $this->success('批量分配成功','');
    }
}
